//导入t_exam_target_to_question模块
const { where } = require('sequelize');
const { Sequelize } = require('sequelize');
const { T_exam_target_to_question } = require('../models/t_exam_target_to_question')

/// 每个课程目标的分数之和
exports.getTargetScore = async (req, res) => {
    const { ACSId, paper_type, target_id } = req.query;

    try {
        let TargetScore = 0
        TargetScore = await T_exam_target_to_question.sum('score', { where: { subid, paper_type, target_id } });

        res.json({
            "code": 200,
            "msg": "查询成功",
            "data": TargetScore
        });

    } catch (error) {
        res.json({
            "code": 500,
            "msg": "查询失败,请重试"
        });
    }
};


/// 每个课程目标的占比
exports.getScoreCentage = async (req, res) => {
    const { subid, paper_type, target_id } = req.query;

    try {
        //课程目标总分
        let PaperScore = 0
        let TargetScore = 0
        TargetScore = await T_exam_target_to_question.sum('score', { where: { subid, paper_type, target_id } });
        PaperScore = await T_exam_target_to_question.sum('score', { where: { subid, paper_type } })
        if (TargetScore == 0) {
            res.json({
                "code": 200,
                "msg": "查询成功",
                "data": `${TargetScore.toFixed(2)}%`
            })
        } else {
            const scoreCentage = ((TargetScore / PaperScore) * 100).toFixed(2)
            res.json({
                "code": 200,
                "msg": "查询成功",
                "data": `${scoreCentage}%`
            })
        }
    } catch (error) {
        res.json({
            "code": 500,
            "msg": "查询失败,请重试"
        });
    }
};

//该试卷的总分
exports.getPaperScore = async (req, res) => {

    const { subid, paper_type } = req.query;
    try {
        let PaperScore = 0
        PaperScore = await T_exam_target_to_question.sum('score', { where: { subid, paper_type } });
        res.json({
            "code": 200,
            "msg": "查询成功",
            "data": PaperScore
        })

    } catch (error) {
        res.json({
            "code": 500,
            "msg": "查询失败"
        })
    }

}

//计算每个题型的占比(总)
exports.getQuestionTypecentage = async (req, res) => {
    const { subid, paper_type } = req.query;

    try {
        // 计算试卷总分
        const TotalScore = await T_exam_target_to_question.sum('score', { where: { subid, paper_type } });
        console.log(TotalScore);
        // 按题型计算分数总和
        const ScoreByQuestionType = await T_exam_target_to_question.findAll({
            attributes: ['question_type', [Sequelize.fn('sum', Sequelize.col('score')), 'total_score']],
            where: { subid, paper_type },
            group: ['question_type']
        });

        // 计算每种题型的分数占比
        const percentageByQuestionType = ScoreByQuestionType.map(item => {
            console.log(item.dataValues.question_type);
            const percentage = TotalScore > 0 ? ((item.dataValues.total_score / TotalScore) * 100).toFixed(2) : 0;
            return {
                [item.dataValues.question_type]: `${percentage}%`
            };
        });

        // 返回查询成功的结果
        res.json({
            "code": 200,
            "msg": "查询成功",
            "data": percentageByQuestionType
        });
    } catch (error) {
        // 返回查询失败的结果
        console.log(error);
        res.json({
            "code": 500,
            "msg": "查询失败，请重试"
        });
    }
};

// 计算每种题型的个数（总）
exports.getnumByQuestionType = async (req, res) => {
    const { ACSId, paper_type } = req.query;

    try {
        // 按题型计算个数总和
        const numByQuestionType = await T_exam_target_to_question.findAll({
            attributes: ['question_type', [Sequelize.fn('sum', Sequelize.col('question_num')), 'total_num']],
            where: { t_user_and_a_c_s_id: ACSId, paper_type },
            group: ['question_type']
        });

        // 返回查询成功的结果，包含不同题型各自的总分
        res.json({
            "code": 200,
            "msg": "查询成功",
            "data": numByQuestionType
        });
    } catch (error) {
        // 返回查询失败的结果
        console.log(error);
        res.json({
            "code": 500,
            "msg": "查询失败，请重试"
        });
    }
};

//每总题型的分数（总）
exports.getScoreByQuestionType = async (req, res) => {
    const { ACSId, paper_type } = req.query;

    try {
        // 按题型计算分数总和
        const ScoreByQuestionType = await T_exam_target_to_question.findAll({
            attributes: ['question_type', [Sequelize.fn('sum', Sequelize.col('score')), 'total_score']],
            where: { t_user_and_a_c_s_id: ACSId, paper_type },
            group: ['question_type']
        });

        // 返回查询成功的结果，包含不同题型各自的总分
        res.json({
            "code": 200,
            "msg": "查询成功",
            "data": ScoreByQuestionType
        });
    } catch (error) {
        // 返回查询失败的结果
        console.log(error);
        res.json({
            "code": 500,
            "msg": "查询失败，请重试"
        });
    }
};


const { T_exam_target } = require('../models/t_exam_target')
// 返回不同课程目标的分数
exports.getTargetTypecentage = async (req, res) => {
    const { ACSId, paper_type } = req.query;

    try {
        // 求试卷总分
        const TotalScore = await T_exam_target_to_question.sum('score', { where: { t_user_and_a_c_s_id: ACSId, paperType: paper_type } });

        // 按课程目标计算分数总和
        const ScoreByTarget = await T_exam_target_to_question.findAll({
            attributes: ['target_id', [Sequelize.fn('sum', Sequelize.col('score')), 'total_score']],
            where: {
                t_user_and_a_c_s_id: ACSId,
                paperType: paper_type
            },
            group: ['target_id']
        });

        // 计算每个课程目标的分数
        const scoresByTarget = await Promise.all(ScoreByTarget.map(async item => {
            console.log(item);
            const target = await T_exam_target.findByPk(item.dataValues.target_id);
            if (target) {
                return {
                    target_name: target.target_name,
                    score: item.dataValues.total_score
                };
            } else {
                return null; // 如果目标不存在，返回 null
            }
        }))

        // 返回查询成功的结果
        res.json({
            "code": 200,
            "msg": "查询成功",
            "data": scoresByTarget.filter(Boolean) // 过滤掉为 null 的项
        });
    } catch (error) {
        // 返回查询失败的结果
        console.log(error);
        res.json({
            "code": 500,
            "msg": "查询失败，请重试"
        });
    }
};

//题库中的题型统计
exports.getnumQuestionType = async (req, res) => {
    const { subid } = req.query;

    try {
        const questions = await T_exam_question.findAll({
            where: {
                sub_id: subid
            }
        });

        // 根据题型进行统计
        const typeCounts = questions.reduce((acc, question) => {
            acc[question.type] = (acc[question.type] || 0) + 1;
            return acc;
        }, {});

        res.json(typeCounts);
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
};